﻿using Godot;

namespace GodotUtilities
{
    public static class AnimationUtilities
    {
        public static SpriteFrames CreateSpriteFrames(Texture2D spriteSheetTexture, IEnumerable<string> animationNames, IEnumerable<int> animationFrameCounts, int frameWidth, int frameHeight = int.MinValue, bool flipX = false)
        {
            // Support rectangular frames
            frameHeight = frameHeight == int.MinValue ? frameWidth : frameHeight;
            // Support flipping the sprite sheet
            if (flipX)
            {
                spriteSheetTexture.GetImage().FlipX();
            }
            SpriteFrames spriteFrames = new();
            int animationIndex = 0;
            foreach (string animationName in animationNames)
            {
                spriteFrames.AddAnimation(animationName);
                spriteFrames.SetAnimationLoop(animationName, true);
                foreach (int frame in Enumerable.Range(0, animationFrameCounts.ElementAt<int>(animationIndex)))
                {
                    Rect2 frameTextureRegion = new(frame * frameWidth, animationIndex * frameHeight, frameWidth, frameHeight);
                    AtlasTexture frameTexture = new()
                    {
                        Atlas = spriteSheetTexture,
                        Region = frameTextureRegion,
                    };
                    spriteFrames.AddFrame(animationName, frameTexture);
                }
                animationIndex++;
            }

            return spriteFrames;
        }
    }
}